<!--
 * @Descripttion:
 * @version:
 * @Editor: E-CHOOSEUS R&D
 * @LastEditors: E-CHOOSEUS R&D
-->
<template>
  <div v-loading="loading" class="index">
    <div class="act-bar">
      <DateQuickPicker
        v-model="search.startTime"
        class="left"
        @change="getPages()"
      />
      <div class="week-box left">
        <i
          class="picker-before el-icon-arrow-left"
          :class="{ disabled: getDisabled('prev') }"
          @click="prevDate"
        ></i>
        <span class="week-num">{{ week }}</span>
        <i
          class="picker-after el-icon-arrow-right"
          :class="{ disabled: getDisabled('next') }"
          @click="nextDate"
        ></i>
      </div>
      <img
        class="refresh left mr-10 ml-10"
        src="@/assets/images/refresh.png"
        @click="reloadPage()"
      />
      <CAFileCancel :documentCode="5" moduleCode="nursingDocument" />
      <el-button v-has="'nursingDoc:export'" type="primary" @click="dzblUpload"
        >电子病历归档</el-button
      >
      <el-button
        v-has="'nursingDoc:export'"
        type="primary"
        @click="signWithoutApperance"
        >CA认证</el-button
      >
      <el-button
        v-has="'nursingDoc:edit'"
        type="primary"
        class="my-btn"
        @click="handleEnter"
        >录 入</el-button
      >
      <el-button
        v-has="'nursingDoc:export'"
        class="my-btn"
        @click="() => handleOutput()"
        >导 出</el-button
      >
      <el-button
        id="printRef"
        v-has="'nursingDoc:export'"
        v-print="printConf"
        class="my-btn"
      >
        打 印
      </el-button>
      <el-button
        v-has="'nursingDoc:export'"
        class="my-btn"
        @click="handlePreview"
        >批量打印</el-button
      >
    </div>
    <div class="multi-container">
      <div id="printDom" class="temperatureChart">
        <mainPage
          v-for="(item, idx) in pages"
          :ref="e => (printDoms[idx] = e)"
          :key="idx"
          :page-data="item"
          :page-num="isBatchPrinting ? idx : week - 1"
          :real-page="isBatchPrinting ? idx : 0"
          :data="data"
        />
      </div>
    </div>
    <Form ref="formRef" :patCur="patCur" @refresh="reloadPage()" />
  </div>
</template>

<script>
import { endOfDay, format, startOfDay } from 'date-fns'
import { cloneDeep } from 'lodash-unified'
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  toRefs,
  watch
} from 'vue'

import { Doc } from '@/api/doc/index.js'
import CAFileCancel from '@/components/CAFileCancel/index.vue'
import { DateQuickPicker } from '@/components/DateQuickPicker'
import { useCA } from '@/hooks'
import { formatTime } from '@/utils/format'
import { numToText } from '@/utils/index.js'
import {
  getElementFnFromInstance,
  getStoreFromInstance
} from '@/utils/instance'

import { useDocExport } from '../../hooks'
import Form from './form.vue'
import mainPage from './mainPage.vue'

export default defineComponent({
  name: 'TemperatureChart',
  components: {
    mainPage,
    Form,
    DateQuickPicker,
    CAFileCancel
  },
  setup(props) {
    const state = reactive({
      printConf: {
        id: 'printDom',
        popTitle: '打印', // 打印配置页上方标题
        extraHead: '', //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: '', // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {}, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback() {}, // 开启打印前的回调事件
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback() {
          closeBatchPrint()
        }, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: '',
        standard: '',
        extraCss: ''
      },
      search: {
        hospitalNumber: '',
        patientIdent: '',
        startTime: formatTime(new Date(), 'yyyy-MM-dd 00:00:00'), // 存的是开始时间
        endTime: ''
      },
      loading: false,
      pages: [],
      data: {},
      printDoms: [],
      formRef: {},
      isBatchPrinting: false, // 是否正在打印
      batchLoading: null //批量打印的loading
    })
    const { $loading, $message, $notify } = getElementFnFromInstance()

    const { handleDocExportMulti } = useDocExport()
    const store = getStoreFromInstance()
    const CA = useCA()

    const patCur = computed(() => store.getters.patCur)

    const isHistory = computed(() => store.getters.isHistory)

    // 当前周数
    const week = computed(() => {
      const currentDate = +new Date(state.search.startTime)
      const rkDate = startRkTime.value
      const differ = currentDate - rkDate
      return differ === 0
        ? 1
        : differ % (7 * 86400000) == 0
        ? differ / (7 * 86400000) + 1
        : Math.ceil(differ / (7 * 86400000))
    })

    // 入科时间
    const startRkTime = computed(() => {
      return formatTime(
        patCur.value.startRkTime,
        'yyyy-MM-dd 00:00:00',
        'timestamp'
      )
    })

    /**
     * 获取禁用状态
     */
    function getDisabled(type) {
      // if (!patCur.value) {
      //   return false
      // }
      // if (type === 'prev') {
      //   return (
      //     +new Date(state.search.startTime) - 7 * 24 * 60 * 60 * 1000 <
      //     startRkTime.value
      //   )
      // }
      // if (type === 'next') {
      //   return (
      //     patCur.value.endCkTime &&
      //     startOfDay(+new Date(state.search.startTime)).getTime() +
      //       7 * 24 * 60 * 60 * 1000 >
      //       startOfDay(patCur.value.endCkTime).getTime()
      //   )
      // }
      return false
    }

    /**
     * 上一个日期
     */
    function prevDate() {
      if (getDisabled('prev')) {
        return
      }
      const rkDate = formatTime(
        patCur.value.startRkTime,
        'yyyy-MM-dd 00:00:00',
        'timestamp'
      )
      const pointDate =
        rkDate + ((week.value > 2 ? week.value : 2) - 2) * 7 * 86400000
      state.search.startTime = startOfDay(new Date(pointDate))
      getPages()
    }

    /**
     * 下一个日期
     */
    function nextDate() {
      if (getDisabled('next')) {
        return
      }
      const rkDate = formatTime(
        patCur.value.startRkTime,
        'yyyy-MM-dd 00:00:00',
        'timestamp'
      )
      const pointDate = rkDate + week.value * 7 * 86400000
      state.search.startTime = new Date(pointDate)
      getPages()
    }

    function reloadPage(cb) {
      if (patCur.value.rkInfo && patCur.value.rkInfo.rkDate) {
        getPages(cb)
      } else {
        $notify({
          type: 'error',
          title: '错误',
          message: '当前病人没有入科时间'
        })
      }
    }

    /**
     * * 数据获取在该页面进行，格式化完成后存入pages渲染mainPage页面
     * * mainPage不写监听等耗内存的方法，尽量简化（因为要渲染多张）
     */
    function getPages(cb) {
      state.loading = true
      const rkTime = isHistory.value
        ? patCur.value.startRkTime
        : patCur.value.rkInfo.rkDate
      const rkDate = state.isBatchPrinting
        ? Number(startOfDay(new Date(rkTime)))
        : Number(startOfDay(new Date(rkTime))) + (week.value - 1) * 7 * 86400000
      setTimeout(() => {
        let obj = {},
          startStamp = rkDate
        const ckTime = patCur.value.eventTime
          ? Number(endOfDay(patCur.value.eventTime))
          : Number(endOfDay(+new Date()))
        const endStamp = state.isBatchPrinting
          ? ckTime
          : rkDate + 7 * 86400000 - 1000
        const pages = [],
          totalPage = Math.ceil((endStamp - startStamp) / 604800000)
        while (pages.length < totalPage) {
          obj = getTimeBoxes(startStamp)
          pages.push({
            startStamp: startStamp,
            timeBoxes: obj.list,
            rkInfo: patCur.value.rkInfo
          })
          startStamp = obj.startTime
        }
        state.pages = pages
        getTempList(cb)
      }, 200)
    }

    /**
     * 获取时间节点
     */
    function getTimeBoxes(startTime) {
      const list = []
      for (let i = 1; i < 43; i++) {
        list.push({
          sTime: startTime,
          eTime: startTime + 14400000
        })
        startTime = startTime + 14400000
      }
      return { list, startTime }
    }

    //格式化数据
    async function getTempList(cb) {
      const rkTime = isHistory.value
        ? patCur.value.startRkTime
        : patCur.value.rkInfo.rkDate
      const startTime = state.isBatchPrinting
        ? Number(startOfDay(new Date(rkTime)))
        : Number(startOfDay(new Date(rkTime))) + (week.value - 1) * 7 * 86400000
      const params = {
        hospitalNumber: patCur.value.hospitalNumber,
        patientIdent: patCur.value.patientIdent,
        rkTime,
        startTime,
        endTime: state.isBatchPrinting
          ? patCur.value.endCkTime
          : startTime + 7 * 86400000 - 1000
      }
      const { data: Model } = await Doc.getTempList(params)
      const pages = cloneDeep(state.pages)
      //初始化各项数据
      const obj = {
          date: [],
          SHDay: [], //术后天数
          event: [],
          temp: [],
          heart: [],
          pain: [],
          breath: [],
          bloodPressure: [],
          shit: [],
          input: [],
          output: [],
          urine: [],
          weight: [],
          bloodSugar: [],
          height: [],
          custom1: [], //自定义项目1
          custom2: [], //自定义项目2
          custom3: [], //自定义项目3
          custom4: [] //自定义项目4
          // flow: []
        },
        breathFirstArr = []
      let page = 0
      while (page < pages.length) {
        obj.date.push(getDateNodes(pages[page].startStamp)) //存放日期
        obj.event.push(loop(42, [])) //事件
        obj.temp.push(
          loop(42, { type: null, val1: null, val2: null, txt: null })
        ) //体温
        obj.heart.push(loop(42, { type: null, val: null })) //心率/脉搏
        obj.pain.push(loop(42, [])) //疼痛
        obj.breath.push(loop(42, { val: null, isHXJ: false, isNumUp: true })) //呼吸
        breathFirstArr.push('') //每页第一次呼吸数组
        obj.bloodPressure.push(loop(14)) //血压
        obj.shit.push(loop(7)) //大便
        obj.input.push(loop(7)) //入量
        obj.output.push(loop(7)) //出量
        obj.urine.push(loop(7)) //尿量
        obj.weight.push(loop(7)) //体重
        obj.height.push(loop(7)) //身高
        obj.custom1.push(loop(7, { val: null, title: null })) //自定义项目1
        obj.custom2.push(loop(7, { val: null, title: null })) //自定义项目2
        obj.custom3.push(loop(7, { val: null, title: null })) //自定义项目3
        obj.custom4.push(loop(7, { val: null, title: null })) //自定义项目4
        // obj.flow.push(loop(7)) //引流量
        obj.bloodSugar.push(loop(7)) //快速血糖
        page++
      }
      //格式化接口数据
      //术后天数
      const arr = []
      Model['listEvent']?.forEach(item => {
        const dateArr = item['hours'].split('-')
        if (item.eventName === '手术') {
          arr.push(
            Date.parse(`${dateArr[0]}-${dateArr[1]}-${dateArr[2]} 00:00:00`)
          )
        }
        const eventArr = ['入院', '出院', '死亡']
        if (eventArr.includes(item.eventName)) {
          const _dateArr = formatTime(item.eventTime, 'HH:mm').split(':')
          item.eventName = `${item.eventName}丨丨${numToText(
            _dateArr[0]
          )}时${numToText(_dateArr[1])}分`
        }
        //穿插事件格式化
        const { x, y } = getXYFromDate(dateArr, 6)
        if (x != undefined && y != undefined) {
          obj.event[x][y].push(item['eventName'])
        }
      })
      obj.SHDay = formatSHDay(arr, obj.date)
      //体温
      for (const item in Model['collectsTw']) {
        const _item = Model['collectsTw'][item]
        const { x, y } = getXYFromDate(item.split('-'), 6)
        let type, val1, val2 //测量类型:type, val1: 第一次测的值, val2: 降温后测的值
        _item.forEach(res => {
          if (res.obsvCode == 'gcx_T') {
            val1 = res.propValue * 1
          } else if (res.obsvCode == 'gcx_clgj') {
            type = res.propValue
          } else if (res.obsvCode == 'gcx_wlywjw') {
            val2 = res.propValue * 1
          } else {
            val1 = 0
            type = 'gcx_clgj_gw'
          }
        })
        if (x != undefined && y != undefined) {
          obj.temp[x][y] = {
            type,
            val1,
            val2
          }
        }
      }
      //脉搏/心率
      for (const item in Model['collectsPulseHeartRate']) {
        const _item = Model['collectsPulseHeartRate'][item]
        const { x, y } = getXYFromDate(item.split('-'), 6)
        if (x != undefined && y != undefined && _item && _item.length > 0) {
          // 优先取心率
          const xl = _item.find(res => res.obsvCode == 'gcx_ecg_s')
          const pr = _item.find(res => res.obsvCode == 'pr')
          obj['heart'][x][y] = {
            val: xl ? xl.propValue : pr.propValue,
            type: xl ? xl.obsvCode : pr.obsvCode
          }
        }
      }
      //疼痛
      for (const item in Model['mapTt']) {
        const _item = Model['mapTt'][item]
        const { x, y } = getXYFromDate(item.split('-'), 6)
        if (x != undefined && y != undefined) {
          _item.map(res => {
            obj.pain[x][y].push(res['showValue'] * 1)
          })
        }
      }
      //呼吸
      let isNumUp = true //是否数字在上
      const breathArr = []
      for (const item in Model['collectsHuxi']) {
        const dateArr = item.split('-')
        breathArr.push({
          timeStamp: Date.parse(
            `${dateArr[0]}-${dateArr[1]}-${dateArr[2]} ${dateArr[3]}:00:00`
          ),
          date: item,
          ...Model['collectsHuxi'][item][0],
          ...getXYFromDate(item.split('-'), 6)
        })
      }
      breathArr.sort((a, b) => a.timeStamp - b.timeStamp)
      const matchedData = {}

      const hoursArr = [2, 6, 10, 14, 18, 22]
      const daiji = []
      if (Model['listHuxiJiHaveR']) {
        Model['listHuxiJiHaveR'].forEach(item => {
          if (item.showType == 1 || item.showType == 2) {
            const startDiffDayHourArr = item.startDiffDayHour.split('-')
            const startDiffDayHourObj = {
              date: startDiffDayHourArr
                .slice(0, startDiffDayHourArr.length - 1)
                .join('-'),
              hour: startDiffDayHourArr[startDiffDayHourArr.length - 1]
            }

            let endDiffDayHourArr
            if (item.endDiffDayHour) {
              endDiffDayHourArr = item.endDiffDayHour.split('-')
            } else {
              endDiffDayHourArr = format(
                new Date().getTime(),
                'yyyy-MM-dd-HH'
              ).split('-')
            }
            const endDiffDayHourObj = {
              date: endDiffDayHourArr
                .slice(0, endDiffDayHourArr.length - 1)
                .join('-'),
              hour: endDiffDayHourArr[endDiffDayHourArr.length - 1]
            }
            const startDayTimestamp = new Date(
              startDiffDayHourObj.date.replace(/-/g, '/') + ' 00:00:00'
            ).getTime()
            const endDayTimestamp = new Date(
              endDiffDayHourObj.date.replace(/-/g, '/') + ' 00:00:00'
            ).getTime()
            const day = parseInt(
              (endDayTimestamp - startDayTimestamp) / 1000 / 60 / 60 / 24,
              10
            )
            for (let i = 0; i <= day; i++) {
              for (let j = 0; j < hoursArr.length; j++) {
                if (
                  hoursArr[j] + i * 24 >= startDiffDayHourObj.hour * 1 &&
                  hoursArr[j] + i * 24 <= endDiffDayHourObj.hour * 1 + day * 24
                ) {
                  daiji.push({
                    isDaiji: item.showType == 1 ? false : !item.isOpen,
                    diffDayHour: format(
                      startDayTimestamp +
                        (hoursArr[j] + i * 24) * 60 * 60 * 1000,
                      'yyyy-MM-dd-H'
                    )
                  })
                }
              }
            }
          }
        })
      }

      breathArr.forEach(res => {
        if (!breathFirstArr[res.x]) {
          isNumUp = true
          breathFirstArr[res.x] = res.propValue
        }
        // obj.breath[res.x][res.y] = { val: res["propValue"], isHXJ: res["createSource"] === "dev", isNumUp };
        const listHuxiJiHaveDaijiItem = daiji.find(
          item => item.diffDayHour == res['date']
        )
        if (listHuxiJiHaveDaijiItem) {
          matchedData[listHuxiJiHaveDaijiItem.diffDayHour] = true
        }
        obj.breath[res.x][res.y] = {
          val: res['propValue'],
          isHXJ:
            listHuxiJiHaveDaijiItem && listHuxiJiHaveDaijiItem.isDaiji !== null
              ? !listHuxiJiHaveDaijiItem.isDaiji
              : false,
          isNumUp
        }
        isNumUp = !isNumUp
      })
      const notMatchedData = daiji.filter(
        item => !matchedData[item.diffDayHour]
      )
      notMatchedData.forEach(item => {
        const { x, y } = getXYFromDate(item.diffDayHour.split('-'), 6)
        if (!breathFirstArr[x]) {
          isNumUp = true
          breathFirstArr[x] = true
        }
        if (x != undefined && y != undefined) {
          obj.breath[x][y] = {
            val: '',
            isHXJ: item.isDaiji !== null ? !item.isDaiji : false,
            isNumUp
          }
        }
        isNumUp = !isNumUp
      })
      //血压
      for (const item in Model['collectsBloodPressure']) {
        const _item = Model['collectsBloodPressure'][item]
        if (_item && _item.length > 0) {
          const { x, y } = getXYFromDate(item.split('-'), 2)
          if (x != undefined && y != undefined) {
            let ibpD = '',
              ibpS = '' //有创舒张压:ibpD, 有创收缩压:ibpS
            _item.forEach(res => {
              if (res.obsvCode == 'ibpD' || res.obsvCode == 'nIbpD') {
                ibpD = res.propValue
              } else if (res.obsvCode == 'ibpS' || res.obsvCode == 'nIbpS') {
                ibpS = res.propValue
              }
            })
            if (x != undefined && y != undefined) {
              obj.bloodPressure[x][y] = `${ibpS}/${ibpD}`
            }
          }
        }
      }

      // 尿量
      for (const item in Model['mapNl']) {
        const _item = Model['mapNl'][item]
        const { x, y } = getXYFromDate(item.split('-'), 1)
        if (x != undefined && y != undefined) {
          obj.urine[x][y] = _item
        }
      }

      // 大便
      for (const item in Model['mapShit']) {
        const _item = Model['mapShit'][item]
        const { x, y } = getXYFromDate(item.split('-'), 1)
        if (x != undefined && y != undefined) {
          obj.shit[x][y] = _item
        }
      }

      // 入量
      for (const item in Model['mapIn']) {
        const _item = Model['mapIn'][item]
        const { x, y } = getXYFromDate(item.split('-'), 1)
        if (x != undefined && y != undefined) {
          obj.input[x][y] = _item
        }
      }

      // 出量
      for (const item in Model['mapOut']) {
        const _item = Model['mapOut'][item]
        const { x, y } = getXYFromDate(item.split('-'), 1)
        if (x != undefined && y != undefined) {
          obj.output[x][y] = _item
        }
      }
      // 快速血糖
      for (const item in Model['mapBloodSugar']) {
        const _item = Model['mapBloodSugar'][item]
        const { x, y } = getXYFromDate(item.split('-'), 1)
        if (x != undefined && y != undefined) {
          obj.bloodSugar[x][y] = _item
        }
      }
      // 体重
      for (const item in Model['mapWeight']) {
        const _item = Model['mapWeight'][item]
        const { x, y } = getXYFromDate(item.split('-'), 1)
        if (x != undefined && y != undefined) {
          obj.weight[x][y] = _item
        }
      }
      // 身高
      for (const item in Model['mapHeight']) {
        const _item = Model['mapHeight'][item]
        const { x, y } = getXYFromDate(item.split('-'), 1)
        if (x != undefined && y != undefined) {
          obj.height[x][y] = _item
        }
      }
      // 自定义项目
      let idx = 1
      for (const item in Model['mapCustom']) {
        // 只取前四个
        if (idx <= 4) {
          const _item = Model['mapCustom'][item]

          for (const customDate in _item) {
            const val = _item[customDate]
            const { x, y } = getXYFromDate(customDate.split('-'), 1)
            if (x != undefined && y != undefined) {
              obj[`custom${idx}`][x][0].title = item
              obj[`custom${idx}`][x][y].val = val
            }
          }
          idx++
        }
      }
      //引流量
      // Model['listOutYll']?.forEach(item => {
      //   const { x, y } = getXYFromDate(item['diffDay'].split('-'), 1)
      //   if (x != undefined && y != undefined) {
      //     obj.flow[x][y] = item['sumValue']
      //   }
      // })
      nextTick(() => {
        state.data = obj
      })
      //循环初始化
      function loop(times, val = '') {
        const arr = []
        let idx = 0
        while (idx < times) {
          arr.push(cloneDeep(val))
          idx++
        }
        return arr
      }
      //获取日期节点
      function getDateNodes(startTime) {
        const list = []
        for (let i = 1; i < 8; i++) {
          list.push(startTime)
          startTime = startTime + 86400000
        }
        return list
      }
      //匹配日期获取xy轴
      function getXYFromDate(dateArr, grid = 1, flag) {
        let timestamp = null
        if (flag) {
          timestamp = Date.parse(
            `${dateArr[3]}-${dateArr[4]}-${dateArr[5]} 00:00:00`
          )
        } else {
          timestamp = Date.parse(
            `${dateArr[0]}-${dateArr[1]}-${dateArr[2]} 00:00:00`
          )
        }
        let x, y, extraY
        if (grid === 1) {
          extraY = 0
        } else if (dateArr[3] === '上午') {
          extraY = 0
        } else if (dateArr[3] === '下午') {
          extraY = 1
        } else {
          // eslint-disable-next-line radix
          extraY = parseInt(dateArr[3] / 4)
        }
        if (!x && !y && timestamp == 1691251200000) {
        }
        obj.date.forEach((res, idx) => {
          if (res[0] <= timestamp && timestamp <= res[6]) {
            x = idx
            res.forEach((_res, _idx) => {
              if (_res === timestamp) {
                y = _idx * grid + extraY
                return
              }
            })
          }
        })
        return { x, y }
      }
      nextTick(() => {
        cb?.()
        state.loading = false
      })
    }

    // 计算术后天数
    function formatSHDay(dateData, dateArr) {
      //手术时间从小到大排序
      const SSDate = dateData.sort((a, b) => a - b),
        dataArr = []
      for (let x = 0; x < state.pages.length; x++) {
        dataArr.push(['', '', '', '', '', '', ''])
      }
      dateArr.map((res, idx) => {
        res.map((_res, _idx) => {
          SSDate.map(date => {
            const diff = Math.ceil((_res - date) / 86400000)
            if (diff > 0 && diff <= 10) {
              const dayArr = dataArr[idx][_idx].split('/')
              dayArr.unshift(diff)
              dataArr[idx][_idx] = dayArr.filter(res => res).join('/')
            }
          })
        })
      })
      return dataArr
    }

    // 录入
    function handleEnter() {
      state.formRef.initData()
    }

    // 导出
    function handleOutput(cb) {
      setTimeout(() => {
        const loading = $loading({ text: '导出中' })
        handleDocExportMulti(state.printDoms, '', '体温单.pdf', () => {
          loading.close()
          cb?.()
        })
      }, 500)
    }

    function signWithoutApperance() {
      state.loading = true
      CA.signWithoutApperance(
        state.printDoms,
        '',
        '体温单.pdf',
        'nursingDocument',
        5,
        () => {
          state.loading = false
        }
      )
    }

    function dzblUpload() {
      state.loading = true
      CA.dzblUpload(
        state.printDoms,
        '',
        '体温单.pdf',
        'nursingDocument',
        5,
        () => {
          state.loading = false
        }
      )
    }

    // 批量打印
    async function handlePreview() {
      state.isBatchPrinting = true
      state.batchLoading = $loading({})

      reloadPage(() => {
        document.querySelector('#printRef').click()
      })
    }

    // 关闭批量打印
    async function closeBatchPrint() {
      if (state.isBatchPrinting) {
        state.isBatchPrinting = false
        reloadPage(() => {
          state.batchLoading.close()
          state.batchLoading = null
        })
      }
    }

    watch(
      patCur,
      val => {
        if (val) {
          if (val.rkInfo && val.rkInfo.rkDate) {
            state.search.startTime = formatTime(
              val.endCkTime || new Date(),
              'yyyy-MM-dd 00:00:00'
            )
            getPages()
          } else {
            $notify({
              type: 'error',
              title: '错误',
              message: '当前病人没有入科时间'
            })
          }
        }
      },
      { deep: true, immediate: true }
    )
    onMounted(() => {
      // handleEnter()
    })
    return {
      ...toRefs(state),
      week,
      patCur,
      // isFlow,
      getDisabled,
      reloadPage,
      handleOutput,
      getPages,
      handleEnter,
      prevDate,
      nextDate,
      handlePreview,
      signWithoutApperance,
      dzblUpload
    }
  }
})
</script>
<style lang="scss" scoped>
.index {
  height: calc(100% - 15px);

  .act-bar {
    min-height: 52px;
    margin-bottom: 10px;
    padding: 9px 10px;
    text-align: right;
    border-bottom: 1px solid #f2f4f5;
  }

  .multi-container {
    height: calc(100% - 30px);
    padding-bottom: 30px;
    overflow-y: auto;
    display: block;
    text-align: center;
  }
}

.temperatureChart {
  width: 1100px;
  // width: 294mm;
  margin: 0 auto;
}

.week-box {
  margin-left: 10px;
  display: inline-flex;
  align-items: center;
  vertical-align: bottom;
  border: 1px solid #c8d0e2;
  background: #fff;
  border-radius: 4px;

  .week-num {
    width: 60px;
    height: 30px;
    line-height: 30px;
    margin-left: -1px;
    text-align: center;
    border-right: 1px solid #c8d0e2;
    border-left: 1px solid #c8d0e2;
  }

  .picker-before,
  .picker-after {
    width: 26px;
    height: 30px;
    opacity: 1;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
    color: #7d869d;
    background: rgb(22 93 255 / 10%);

    &.disabled {
      cursor: not-allowed;
    }
  }

  .picker-after {
    margin-left: -1px;
    border-radius: 0 4px 4px 0;
  }
}

.refresh {
  width: 32px;
  padding: 8px;
  background: #155ef3;
  border-radius: 4px;
  cursor: pointer;
  vertical-align: top;
}
</style>
